package ua.com.alus.resvac.crm.services.spring;

import org.springframework.transaction.annotation.Transactional;
import ua.com.alus.resvac.crm.domen.dao.CityDao;
import ua.com.alus.resvac.crm.domen.dao.ProfessionAreaDao;
import ua.com.alus.resvac.crm.domen.dao.RegionDao;
import ua.com.alus.resvac.crm.domen.entities.City;
import ua.com.alus.resvac.crm.domen.entities.ProfessionArea;
import ua.com.alus.resvac.crm.domen.entities.Region;

import java.util.List;

/**
 * Created by Usatov Alexey
 */
public class BaseServiceImpl implements BaseService {

    private List<Region> regions;

    private static final Integer LOCK = 1;

    private RegionDao regionDao;
    private List<ProfessionArea> professionAreas;

    private ProfessionAreaDao professionAreaDao;

    public ProfessionAreaDao getProfessionAreaDao() {
        return professionAreaDao;
    }

    public void setProfessionAreaDao(ProfessionAreaDao professionAreaDao) {
        this.professionAreaDao = professionAreaDao;
    }

    public RegionDao getRegionDao() {
        return regionDao;
    }

    public void setRegionDao(RegionDao regionDao) {
        this.regionDao = regionDao;
    }

    private CityDao cityDao;

    public CityDao getCityDao() {
        return cityDao;
    }

    public void setCityDao(CityDao cityDao) {
        this.cityDao = cityDao;
    }

    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public List<Region> getRegions() {
        synchronized (LOCK) {
            if (regions == null) {
                regions = getRegionDao().getEntityManager().createNamedQuery(Region.SELECT_ALL_QUERY).getResultList();
            }
        }
        return regions;
    }

    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public List<City> getCities(Integer regionId) {
        return getCityDao().getEntityManager().createNamedQuery(City.SELECT_CITY_BY_REGION_ID).setParameter("regionId", regionId).getResultList();
    }

    @Override
    @Transactional(readOnly = true)
    public City getCityByUuid(Integer id) {
        return getCityDao().findById(id);
    }

    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public List<ProfessionArea> getProfessionAreas() {
        synchronized (LOCK) {
            if (professionAreas == null) {
                professionAreas = getProfessionAreaDao().getEntityManager().
                        createNamedQuery(ProfessionArea.SELECT_ALL_QUERY).getResultList();
            }
            return professionAreas;
        }
    }
}
